package diona.components

import net.liftweb.util.CssSel
import diona.search.PostInfo
import net.liftweb.http.{SHtml, Templates}
import xml.NodeSeq
import net.liftweb.http.js.JsCmds.Script
import net.liftweb.http.js.{JsCmds, JsCmd}
import org.joda.time.{Days, LocalDate}
/**
 * User: anton
 * Date: 09.07.11 23:55
 */
class PostsComponent(val posts: Seq[PostInfo], val onPostClick: Option[PostInfo => JsCmd] = None)
  extends SnippetsUtil
{
  def render(): NodeSeq =
  {
    val template: NodeSeq = Templates(List("templates-hidden", "posts")).open_!
    bindCss(template)
  }

  def distributionByDates: Seq[(LocalDate, Int)] =
  {
    val comparator = Ordering.fromLessThan[LocalDate](_.isBefore(_))

    val postsByDates = posts.groupBy(_.tstamp.toLocalDate)
    val minDate = postsByDates.keySet.min(comparator)
    val maxDate = postsByDates.keySet.max(comparator)
    for {
      i <- 0 to Days.daysBetween(minDate, maxDate).getDays
      day = minDate.plusDays(i)
    } yield {
      day -> postsByDates.getOrElse(day, List()).length
    }
  }

  def distributionByDatesAsJs: String =
  {
    val distribution = distributionByDates.map(t => {"['" + formatDate(Some(t._1)) + "'," + t._2 + "]"})
    "[" + distribution.mkString(",") + "]"
  }

  private lazy val bindCss: CssSel = {
    "#chartScript" #> Script(JsCmds.Run("showDistributionByDate('chartByDays', " + distributionByDatesAsJs + ");")) &
      "#itemsCount" #> posts.length &
      ".postItemWrapper *" #> posts.map(t => {
        ".postItemDate *" #> dateTimeFormatter.print(t.tstamp) &
          ".postItemTitle *" #> t.title.getOrElse("") &
          ".postItemText *" #> PostDetailsComponent.textAsHtml(t) &
          ".postItemUrl *" #> {
            "a [href]" #> t.url & "a *" #> t.url
          } &
          ".postItemSite *" #> {
            "a [href]" #> ("http://" + t.site) & "a *" #> t.site
          } &
          ".postItemAuthor *" #> {
            t.author match {
              case None => "*" #> ""
              case Some(url) if url.startsWith("http") => {
                "a [href]" #> url & "a *" #> url
              }
              case Some(name) => "*" #> name
            }
          } &
          ".postItem [onclick]" #> onPostClick.map(handler => SHtml.ajaxInvoke(() => handler(t)))
      })
  }
}